/*******************************************************************
 *
 * Copyright (C), 2021-2022, LS, All rights reserved.
 *
 * Author      : 
 * Create Time : 2021-09-22
 * Version     : v0.1
 * Description : 
 *******************************************************************/
 
/*----------------------------Head file----------------------------*/
#include "flash.h"
#include "app_time.h"
#include "app_reset.h"
#include "app_global_data.h"
#include "bsp_hw_config.h"
#include "user_config.h"

#define APP_RESET_LOG_EN    0

#if APP_RESET_LOG_EN
#include "log.h"
#define APP_RST_LOG         LOG_DEBUG
#else
#define APP_RST_LOG(...)
#endif

/*----------------------------macro file---------------------------*/
#define hal_store_erase_sector  hal_flash_erase_sector
#define hal_store_write         hal_flash_write
#define hal_store_read          hal_flash_read

/*----------------------------type define--------------------------*/

/*----------------------------var define---------------------------*/

/*-------------------------func declaration------------------------*/

/*-----------------------------------------------------------------*/

void app_system_reset(void)
{
    timebase_t tb;

    app_datetime_sync_handler();
    tb.info.tm_base = app_time_tim_base_get();
    tb.info.snapshot = app_time_snapshot_get();
    if(tb.info.tm_base <= 0) {
        app_platform_reset();
        return;
    }

    tb.id = SOFT_RESET_VALID_ID;
    hal_store_erase_sector(TEMP_DATA_RST_ADDR);
    hal_store_write(TEMP_DATA_RST_ADDR, (uint8_t*)&tb, sizeof(tb));
    app_platform_reset();
}


void app_ship_mode_reset(void)
{
    uint16_t reset_reason = SHIP_MODE_VALID_ID;

    hal_store_erase_sector(TEMP_DATA_RST_ADDR);
    hal_store_write(TEMP_DATA_RST_ADDR, (uint8_t*)&reset_reason, sizeof(reset_reason));
    app_platform_reset();
}


uint8_t app_system_reset_reason_get(void)
{
    uint16_t reset_reason = RST_REASON_NULL;
    hal_store_read(TEMP_DATA_RST_ADDR, (uint8_t*)&reset_reason, sizeof(reset_reason));
    if(SOFT_RESET_VALID_ID == reset_reason) {
        //Do not erase here, we need read base time later.
        return RST_REASON_SOFT_RST;
    }
    if(SHIP_MODE_VALID_ID == reset_reason) {
        hal_store_erase_sector(TEMP_DATA_RST_ADDR);
        return RST_REASON_SHIP_MODE_ENTER;
    }
    else if(SHIP_MODE_WAKE_ID == reset_reason) {
        hal_store_erase_sector(TEMP_DATA_RST_ADDR);
        return RST_REASON_SHIP_MODE_WAKE;
    }
    else {
        return RST_REASON_NULL;
    }
}


void app_system_reset_data_init(void)
{
    timebase_t tb;

    g_app_data.sys.rst_reason = app_system_reset_reason_get();
    if(RST_REASON_SOFT_RST == g_app_data.sys.rst_reason) {
        hal_store_read(TEMP_DATA_RST_ADDR, (uint8_t*)&tb, sizeof(tb));
        app_time_set_dt_cfg(&tb.info);
        hal_store_erase_sector(TEMP_DATA_RST_ADDR);
    }
    else {
        app_set_default_datetime();
    }
}

